/**
 * Messages Interaction
 * Handle inbox, outbox and draft selections and actions
 *
 * @author Seth
 * @version 0.1
 */
var Msgint = function() {
	var trans = {},
		// selection interaction
		selection = function() {
			var m = $('input[class="master"]'),
				s = $('input[class="slave"]'),
				d = $('input[name="mass_selection"]');

			// auto check?
			if(d.length > 0) {
				$.each(d.val().split(','), function(s, i){
					$('input[rel="'+ i +'"]').get(0).checked = true;
				});

				__doit();
			}

			// bind event on master
			m.click(function(){
				__doit(function(i){
					if(!i.disabled)
						i.checked = m.get(0).checked;
				});
			});

			// will check or uncheck based on master
			function __doit(f) {
				var x = 0;

				s.each(function(s, i) {
					if(typeof(f) == 'function')
						f.call(this, i);
					if(i.checked)
						x++;
				});
			};

		// to send or not to send, that is the question.
		},	send = function(e) {
			var x = 0,
				i = $(e.currentTarget),
				s = $('input[class="slave"]'),
				d = {
					mass_action: i.attr('name'),
					items: []
				};

			// check all our slaves, muhahah
			s.each(function(s, i) {
				if(i.checked){
					d.items.push($(i).attr('rel'));
					x++;
				}
			});

			// do we have slaves selected?
			if(x > 0) {
				post(document.URL, d);

			// no slaves, boring error
			} else Petolio.showMessage(trans.error);

		// create a dom form to post stuff with it
		},	post = function(u, p) {
			var f = ['<form method="POST" action="'+ u +'">'];

			// are we delete? require confirmation then
		    if(p.mass_action == 'delete')
				Petolio.showConfirm(trans.reqconf, __send);

			// usual action, no requests
		    else __send();

		    // create and send the form
			function __send() {
			    f.push('<input type="hidden" name="mass_action" value="'+ p.mass_action +'"/>');
			    for(var k in p.items) f.push('<input type="hidden" name="mass_items[]" value="'+ p.items[k] +'"/>');
			    f.push('</form>');

			    $(f.join('')).appendTo('body').get(0).submit();
			};

		// bind events
		},	bind = function() {
			$('input[name="read"]').click(send);
			$('input[name="delete"]').click(send);

		// constructor
		},	__construct = function(t) {
			trans = t;
			bind();
			selection();
		};

	// public
	return {
		init: __construct
	};
}();